<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="450px" :title="`${drawerProps.title}工序`">
    <el-form
      ref="ruleFormRef"
      label-width="100px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
    >
      <el-form-item label="工序编号" prop="processId">
        <el-input v-model="drawerProps.row!.processId" placeholder="请填写工序编号" clearable />
      </el-form-item>
      <el-form-item label="工序名称" prop="processName">
        <el-input v-model="drawerProps.row!.processName" placeholder="请填写工序名称" clearable />
      </el-form-item>
      <el-form-item label="工序类型" prop="isTransport">
        <el-select v-model="drawerProps.row!.isTransport" placeholder="请选择工序类型">
          <el-option label="运输工序" :value="1" />
          <el-option label="生产工序" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="工序描述" prop="description">
        <el-input type="textarea" v-model="drawerProps.row!.description" placeholder="请填写工序描述" clearable :rows="5" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false">取消</el-button>
      <el-button type="primary" v-show="!drawerProps.isView" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="ProcessDrawer">
import { ref, reactive, defineEmits } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { Process } from "@/api/interface";
import axios from "axios";

// 基础 URL
const baseUrl = import.meta.env.VITE_BASE_URL;

const rules = reactive({
  processId: [{ required: true, message: "请填写工序编号" }], // 工序编号
  processName: [{ required: true, message: "请填写工序名称" }], // 工序名称
  isTransport: [{ required: true, message: "请选择工序类型" }], // 工序类型
  description: [{ required: true, message: "请填写工序描述" }] // 工序描述
});

interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<Process.ResProcess>;
  //   api?: (params: any) => Promise<any>;
  //   getTableList?: () => void;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {}
});

// 向父组件派发刷新事件
const emit = defineEmits(["refresh"]);

// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
};

function formatDate(date: Date): string {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份从0开始，因此需要加1
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      if (drawerProps.value.title === "新增") {
        // 构造请求体
        const payload: any = {
          processId: drawerProps.value.row.processId,
          processName: drawerProps.value.row.processName,
          description: drawerProps.value.row.description,
          isTransport: drawerProps.value.row.isTransport,
          createTime: formatDate(new Date())
        };

        try {
          const resp = await axios.post(`${baseUrl}/api/carbon/createProcess`, payload);
          if (resp.data && resp.data.code === 200) {
            ElMessage.success("新增工序成功");
            emit("refresh");
            drawerVisible.value = false;
          }
        } catch (err: any) {
          const respData = err?.response?.data;
          if (respData && respData.msg) {
            ElMessage.error(respData.msg);
          } else {
            ElMessage.error("新增工序失败，请稍后重试");
          }
        }
      } else if (drawerProps.value.title === "编辑") {
        // 构造请求体
        const payload: any = {
          id: drawerProps.value.row.id, // 主键 ID 必填
          processId: drawerProps.value.row.processId,
          processName: drawerProps.value.row.processName,
          description: drawerProps.value.row.description,
          isTransport: drawerProps.value.row.isTransport
        };

        // 保留创建时间，如果后端需要
        if (drawerProps.value.row.createTime) {
          payload.createTime = drawerProps.value.row.createTime;
        }

        try {
          console.log("修改工序请求体:", payload);
          const resp = await axios.post(`${baseUrl}/api/carbon/updateProcess`, payload);
          if (resp.data && resp.data.code === 200) {
            ElMessage.success("修改工序成功");
            emit("refresh"); // 通知父组件刷新
            drawerVisible.value = false;
          }
        } catch (err: any) {
          const respData = err?.response?.data;
          if (respData && respData.msg) {
            ElMessage.error(respData.msg);
          } else {
            ElMessage.error("修改工序失败，请稍后重试");
          }
        }
      }
    } catch (error) {
      console.log(error);
      ElMessage.error("操作失败，请稍后重试");
    }
  });
};

defineExpose({
  acceptParams
});
</script>
